<?php
/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/ZendSkeletonApplication for the canonical source repository
 * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */

namespace Application;

use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;
use Zend\Db\Adapter\Adapter as DbAdapter;
use Zend\Session\Config\SessionConfig;
use Zend\Session\SessionManager;
use Zend\Session\Container;
use Zend\Authentication\Adapter\DbTable as DbTableAuthAdapter;
use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
use Zend\Authentication\Storage;
use Zend\Authentication\AuthenticationService;


class Module
{
	
	public  static $_instance;
	public function onBootstrap(MvcEvent $e)
    {
    	$_instance = $e;
        $eventManager        = $e->getApplication()->getEventManager();       
        $moduleRouteListener = new ModuleRouteListener();
        $moduleRouteListener->attach($eventManager);
        
      
       //  $translator = $e->getApplication()->getServiceManager()->get('translator');
        // $translator->setLocale($userlanguage);
         
    //     define('event', $translator);
         $_instance  = $e->getApplication();
        
//         $translator->setLocale(LANGUE);
        $this->initializeSession($e);
        
        $this -> initAcl($e);
        $e -> getApplication() -> getEventManager() -> attach('route', array($this, 'checkAcl'));
        
      
    }

    public function initAcl(MvcEvent $e) {
    
    	$acl = new \Zend\Permissions\Acl\Acl();
    	$roles = include __DIR__ . '/config/moduleAclRoles.php';
    	$allResources = array();
    	foreach ($roles as $role => $resources) {
    
    		$role = new \Zend\Permissions\Acl\Role\GenericRole($role);
    		$acl -> addRole($role);
    
    		$allResources = array_merge($resources, $allResources);
    
    		//adding resources
    		foreach ($resources as $resource) {
    			// Edit 4
    			if(!$acl ->hasResource($resource))
    				$acl -> addResource(new \Zend\Permissions\Acl\Resource\GenericResource($resource));
    		}
    		//adding restrictions
    		foreach ($allResources as $resource) {
    			$acl -> allow($role, $resource);
    		}
    	}
    	
    	//setting to view
    	$e -> getViewModel() -> acl = $acl;
    
    }
    
    public function checkAcl(MvcEvent $e) {
    	$route = $e -> getRouteMatch() -> getMatchedRouteName();
    	//you set your role
    	$userRole = 'guest';
    
    	if (!$e -> getViewModel() -> acl ->hasResource($route) || !$e -> getViewModel() -> acl -> isAllowed($userRole, $route)) {
    	    		
    		$response = $e -> getResponse();
    		//location to page or what ever
    		$response -> getHeaders() -> addHeaderLine('Location', $e -> getRequest() -> getBaseUrl() . '/not_found_template');
    		$response -> setStatusCode(404);
    
    	}
    }
    
    public function getConfig()
    {
        return include __DIR__ . '/config/module.config.php';
    }

    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                ),
            ),
        );
    }
    
    public function initializeSession($em)
    {
    	$config = $em->getApplication()->getServiceManager()
  						->get('Config');
    
    	$sessionConfig = new SessionConfig();
    	$sessionConfig->setOptions($config['session']);
    
    	$sessionManager = new SessionManager($sessionConfig);
    	$sessionManager->start();
    
    	Container::setDefaultManager($sessionManager); //au cas ou on utilise plusieurs SessionManagers
    }
    
   
    
  /*  public function appli(){
    	
    	echo 'dans appli';
    	if (!isset(self::$_instance)) {
    		
    		try {
    			self::$_instance = $_instance;
    		} catch (Exception $ex) {
    			echo  $ex;
    		}
    		;
    	}
    	return $_instance;
    }
    
  */  
    
/*public function getServiceConfig()
    {
    	return array(
    			'factories' => array(
    					'db-adapter' => function($sm) {
    						$config = $sm->get('config');
    						$config = $config['db'];
    						$dbAdapter = new DbAdapter($config);
    						return $dbAdapter;
    					},
    			),
    	);
    }
*/

    public function getServiceConfig()
    {
    	return array(
    			'factories'=>array(
    					'Application\Model\MyAuthStorage' => function($sm){
    						return new \Application\Model\MyAuthStorage('zf_tutorial');
    					},
    					 
    					'AuthService' => function($sm) {
    						//My assumption, you've alredy set dbAdapter
    						//and has users table with columns : user_name and pass_word
    						//that password hashed with md5
    						$dbAdapter           = $sm->get('Zend\Db\Adapter\Adapter');
    						$dbTableAuthAdapter  = new DbTableAuthAdapter($dbAdapter,
    								'users','user_name','pass_word', 'MD5(?)');
    						 
    						$authService = new AuthenticationService();
    						$authService->setAdapter($dbTableAuthAdapter);
    						$authService->setStorage($sm->get('Application\Model\MyAuthStorage'));
    
    						return $authService;
    					},
    			),
    	);
    }

}
